<?php

namespace App\Base\Middleware;

use App\Base\Exceptions\ApiException;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\ParameterBag;


class RequsetDataMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $data=$request->input("data");
        if(!empty($data)){
            try {
                $content = $this->decrypt( $request->input("data"));


            } catch (\Exception $exception) {
                throw  new ApiException(ApiException::ERROR_DECTY_NOT_ENABLE);
            }
        }else{
            $content=json_encode([]);
        }


        return $next($this->putIn($request, $content));
    }



    /**
     * decrypt the content
     * @param string $content
     * @return string
     */
    protected function decrypt($content)
    {

       return base64_decode($content);

    }

    /**
     * put the decrypt data into request
     * @param Request $request
     * @param string $content
     * @return Request
     */
    public  function putIn(Request $request, $content)
    {
        $arr=json_decode($content,true);
        $request->merge($arr);
        return $request;
    }


}
